package cn.lyq.card.ui.setting

import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.Const
import cn.lyq.card.manager.PhoneCodeManager
import cn.lyq.card.ui.result.ResultActivity
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_pwd_update.*

class PwdUpdateActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(SettingVM::class.java)
    }

    override fun getLayoutId(): Int {
        return R.layout.act_pwd_update
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_update_login_pwd)

    }

    override fun initListener() {
        super.initListener()

        tvGetCode.setClick {
            PhoneCodeManager.sendMsgCode(6)
        }

        tvConfirm.setClick {
            val pwd = etNewPwd.text.toString()
            if (pwd.isEmpty() || pwd.length < Const.PWD_LENGTH_MIN) {
                ToastUtils.showShort(etNewPwd.hint)
                return@setClick
            }

            val pwdConfirm = etConfirmPwd.text.toString()
            if (pwdConfirm.isEmpty()) {
                ToastUtils.showShort(etConfirmPwd.hint)
                return@setClick
            }
            if (pwd != pwdConfirm) {
                ToastUtils.showShort(R.string.str_pwd_confrim_un_equal)
                return@setClick
            }
            val code = etCode.text.toString()
            if (code.isEmpty()) {
                ToastUtils.showShort(etCode.hint)
                return@setClick
            }

            mModel.upLoginPwd(pwd, code).observe(this, Observer {
                when (it?.status) {
                    Status.LOADING -> {
                        showLoading()
                    }
                    Status.SUCCESS -> {
                        ToastUtils.showShort("修改成功")
                        dismissLoading()
                        ResultActivity.start(this, 0)
                        finish()
                    }
                    Status.ERROR -> {
                        dismissLoading()
                        ToastUtils.showShort(it.message.getMsg())
                    }
                }
            })
        }
    }

    override fun initObserver() {
        super.initObserver()
        PhoneCodeManager.countDown.observe(this, PhoneCodeManager.observer(tvGetCode))
    }

    override fun onDestroy() {
        super.onDestroy()
        PhoneCodeManager.reset()
    }
}